package org.victoria.csms.controller;

import com.alibaba.fastjson.JSONObject;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.util.DigestUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.victoria.common.controller.BaseController;
import org.victoria.common.domain.Page;
import org.victoria.common.utils.FrontUtils;
import org.victoria.common.utils.ResponseUtil;
import org.victoria.common.utils.StringUtils;
import org.victoria.csms.domain.User;
import org.victoria.csms.service.UserService;
import sun.misc.BASE64Encoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by thanatos on 15-6-3.
 */
@Controller
public class UserController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired private UserService manager;

    @RequestMapping("/admin/user/list.htm")
    public String list(Model model, Integer pageNum, String name, String username){
        pageNum = pageNum == null ? 1 : pageNum;
        Page<User> page = manager.getList(pageNum, name, username);
        model.addAttribute(page);
        model.addAttribute("name", name);
        model.addAttribute("username", username);
        return "admin/user/list";
    }

    @RequestMapping(value = "/admin/user/register.htm", method = RequestMethod.GET)
    public String register(User user, String username, Model model){
        if(!StringUtils.isEmpty(username)){
            user = manager.getUserByAccount(username);
        }
        model.addAttribute("user", user);
        return "admin/user/save_update";
    }

    @RequestMapping(value = "/admin/user/register.htm", method = RequestMethod.POST)
    public String register(@Valid User user, BindingResult result){
        if (result.hasErrors()){
            logger.error("user form has error");
            return "admin/user/save_update";
        }
        user.setCreateTime(new Date());
        try {
            manager.saveOrUpdate(user);
        }catch(Exception e){
            user.setUsername("");
            result.reject("username", "帐号已存在");
            return "admin/user/save_update";
        }
        return "redirect:/admin/user/list.htm";
    }

    @RequestMapping("/admin/user/delete.htm")
    public void delete(Long id, HttpServletResponse response){
        JSONObject object = ResponseUtil.getJsonObject();
        if (id==null){
            object.put("code", 1);
            object.put("message", "The parameter had mistake");
            ResponseUtil.renderJson(response, object.toJSONString());
        }
        manager.deleteById(id);
        object.put("code",0);
        object.put("message", "delete successful");
        ResponseUtil.renderJson(response, object.toJSONString());
    }

    @RequestMapping(value = "/login.htm", method = RequestMethod.GET)
    public String login(){
        return "admin/login";
    }

    @RequestMapping(value = "/login.htm", method = RequestMethod.POST)
    public String login(String username, String password, HttpServletRequest request, HttpServletResponse response, Model model){
        Map<String, String> result = new HashMap<String, String>();
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            result.put("login", "账号密码不能为空");
            model.addAttribute("errors", result);
            return "admin/login";
        }
        User user = manager.getByAccAndPass(username, password);
        if (user == null){
            result.put("login", "没有这个账号");
            model.addAttribute("errors", result);
            return "admin/login";
        }
        UsernamePasswordToken token = new UsernamePasswordToken();
        token.setUsername(user.getUsername());
        token.setPassword(user.getPassword().toCharArray());
//        token.setRememberMe(true);
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        request.getSession().setAttribute(FrontUtils.USER_KEY, user);
        Cookie cookie = new Cookie(FrontUtils.AUTO_LOGIN_FIELD, new BASE64Encoder().encode(username.getBytes())+"_"+
                new BASE64Encoder().encode(DigestUtils.md5DigestAsHex(password.getBytes()).getBytes()));
        cookie.setMaxAge(7*24*60*60);
        cookie.setPath("/");
        response.addCookie(cookie);
        return FrontUtils.REDIRECT_TO_INDEX;
    }

    @RequestMapping("/logout.htm")
    public String logout(HttpServletRequest request, HttpServletResponse response){
        Cookie cookies[] = request.getCookies();
        for (Cookie cookie : cookies){
            if (cookie.getName().equals(FrontUtils.AUTO_LOGIN_FIELD)){
                cookie.setMaxAge(0);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
        SecurityUtils.getSubject().logout();
        request.getSession().removeAttribute(FrontUtils.USER_KEY);
        return FrontUtils.REDIRECT_TO_INDEX;
    }

    @RequestMapping(value = "/admin/user/update/password.htm", method = RequestMethod.POST)
    public void update_password(String new_password, String old_password, HttpServletRequest request, HttpServletResponse response){
        logger.error("user update password......");
        JSONObject object = ResponseUtil.getJsonObject();
        User user = (User) request.getSession().getAttribute(FrontUtils.USER_KEY);
        user = manager.getUserByAccount(user.getUsername());
        if (old_password.equals(user.getPassword())){
            manager.updatePassword(user.getId(), new_password);
        }else {
            object.put("code", 1);
            object.put("message", "密码错误");
            ResponseUtil.renderJson(response, object.toJSONString());
            return;
        }
        object.put("code", 0);
        object.put("message", "更新成功");
        ResponseUtil.renderJson(response, object.toJSONString());
    }

    @RequestMapping(value = "/admin/user/update/password.htm", method = RequestMethod.GET)
    public String update_password(){
        return "admin/user/update_password";
    }


}
